package org.dawning.shop.inventory.command.handler;

import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.model.Aggregate;
import org.axonframework.commandhandling.model.Repository;
import org.dawning.shop.common.commands.inventory.ReleaseInventoryCommand;
import org.dawning.shop.common.commands.inventory.ReserveInventoryCommand;
import org.dawning.shop.common.events.inventory.InventoryReleaseEvent;
import org.dawning.shop.common.events.inventory.InventoryReserveEvent;
import org.dawning.shop.inventory.command.aggregate.InventoryAggregate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static org.axonframework.commandhandling.model.AggregateLifecycle.apply;

/**
 * Created by Cc on 2017/6/9.
 */
@Component
public class InventoryHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private Repository<InventoryAggregate> repository;


    @CommandHandler
    public void on(ReleaseInventoryCommand command) {
        logger.info("apply Release inventory command : " + command.toString());
        //apply(new InventoryReleaseEvent(command.getOrderId(),command.getInventoryId(),command.getAmount()));
    }

    @CommandHandler
    public void on(ReserveInventoryCommand command) {
        logger.info("apply Reserve inventory command : " + command.toString());
        Aggregate<InventoryAggregate> aggregate = repository.load(command.getInventoryId());
        aggregate.execute(aggregateRoot->aggregateRoot.reserve(command.getOrderId(),command.getQuantity()));
    }

}
